<script setup>
import { watch, ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { Calendar, Menu, Search } from '@element-plus/icons-vue';
import Profile from './Home components/Profile.vue';
import HomePageFooter from '@/views/Front/Home components/HomePageFooter.vue';
import { useRouter, useRoute } from 'vue-router';
import { storeToRefs } from 'pinia'
import { useArticleStore } from '@/stores/articleStore'

const router = useRouter();
const route = useRoute();
const articleStore = useArticleStore()
const {
  articles,
  categorys,
  pageNum,
  total,
  pageSize,
  categoryId,
  search,
  filteredArticles,
  fetchArticleById,
} = storeToRefs(articleStore)

const showDetail = ref(false);
const currentArticle = ref(null);

onMounted(() => {
  window.scrollTo(0, 0)
  articleStore.fetchCategories()
  articleStore.fetchArticles()
  checkRouteParams()
})

onBeforeUnmount(() => {
  window.scrollTo(0, 0)
  articleStore.fetchArticles()
})

watch(() => route.params.id, checkRouteParams)

function checkRouteParams() {
  const articleId = route.params.id
  if (articleId) {
    viewArticle(articleId)
  } else {
    showDetail.value = false
    currentArticle.value = null
  }
}

watch(search, () => {
  articleStore.fetchArticles()
})

// 文章详情页
const viewArticle = async (articleId) => {
  const article = articles.value.find(a => a.id === parseInt(articleId))
  if (article) {
    currentArticle.value = article;
    showDetail.value = true;
    window.scrollTo(0, 0);
  } else {
    // If the article is not in the current list, fetch it from the server
    try {
      const fetchedArticle = await articleStore.fetchArticleById(articleId)
      currentArticle.value = fetchedArticle
      showDetail.value = true
      window.scrollTo(0, 0)
    } catch (error) {
      console.error('Failed to fetch article:', error)
      // Handle error (e.g., show a notification or redirect to a 404 page)
    }
  }
};

// 文章详情页返回列表
const backToList = () => {
  showDetail.value = false;
  currentArticle.value = null;
  router.push({ name: 'ArticleView' });
}

</script>
<template>
  <div class="article-view-container">
    <div class="article-view">
      <div class="article-view-left">
        <Profile/>
        <el-card class="search" :body-style="{ padding: '0 5px', width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }">
          <div class="search-box">
            <el-input  
            class="search-input" 
            v-model="search" 
            placeholder="搜索文章..." 
            :prefix-icon="Search"/>
          </div>
        </el-card>
        <el-card class="article-view-left-other" shadow="never" :body-style="{ padding: '15px 0 0 0', height: '100%' }">  
          <div class="article-view-left-other-header">
            <span>分类</span>
            <el-button class="reset" @click="articleStore.fetchArticles(categoryId = '')">重置</el-button>
          </div>
          <div class="article-view-left-other-content">
            <el-menu
              class="article-view-content-menu"
              :collapse="false"
            > 
              <el-menu-item 
                v-for="category in categorys" 
                :key="category.id"
                :index="String(category.id)"
              >
                <div class="menu-item-content" @click="articleStore.fetchArticles(categoryId = category.id)">
                  <span class="category-name">{{ category.categoryName }}</span>
                  <span class="count-badge">{{ category.articleCount }}</span>
                </div>
              </el-menu-item>
            </el-menu>
          </div>
        </el-card>
      </div>
      <div class="article-view-right">
        <!-- 文章列表 -->
        <template v-if="!showDetail">
          <el-card 
              v-for="article in filteredArticles" 
              :key="article.id"
              class="article-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <div class="article-content">
                <div class="article-info">
                  <h3 class="article-title" @click="viewArticle(article.id)">
                    {{ article.title }}
                  </h3>
                  <div class="article-else">
                    <span class="icon">
                      <el-icon><Calendar /></el-icon>
                    </span>
                    <span class="text">
                      {{ article.createTime.split(' ')[0] }}
                    </span>
                    <span class="icon" style="margin-left: 30px;">
                      <el-icon><Menu /></el-icon>
                    </span>
                    <span class="text-category"  @click="articleStore.fetchArticles(categoryId = article.categoryId)" style="cursor: pointer;" @mouseover="hover = true" @mouseleave="hover = false" >  
                      {{ article.categoryName }}
                    </span>
                  </div>
                </div>
                <el-image 
                  :src="article.image" 
                  fit="cover"
                  class="article-image"
                />
              </div>
          </el-card>

          <div class="pagination">
            <el-pagination background 
            :page-sizes="[5, 10, 20]"
            layout="prev,pager,next,sizes"
            :total="total" 
            :page-size="pageSize" 
            :current-page="pageNum" 
            @size-change="articleStore.onSizeChange"
            @current-change="articleStore.onCurrentChange" 
            />
          </div>
        </template>
        <!-- 文章详情 -->
        <template v-else>
          <el-card class="article-detail">
            <el-button class="back-button" @click="backToList">
              ←返回
            </el-button>
          <div class="detail-header">
            <h1 class="detail-title">{{ currentArticle.title }}</h1>
            <div class="detail-meta">
              <span class="icon">
                <el-icon><Calendar /></el-icon>
              </span>
              <span class="text">
                {{ currentArticle.createTime.split(' ')[0] }}
              </span>
              <span class="icon" style="margin-left: 30px;">
                <el-icon><Menu  /></el-icon>
              </span>
              <span class="text-category">  
                {{ currentArticle.categoryName }}
              </span>
            </div>
          </div>
          <div class="detail-content" v-html="currentArticle.content"></div>
          </el-card>
        </template>
      </div>
    </div>
    <HomePageFooter/>
  </div>
</template>
<style scoped>
.article-view-container {
  margin: 80px 20vw 0 20vw;
  /* background-color: #99e4ff; */
  height: auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.article-view {
  height: auto;
  width: 100%;
  min-height: 100vh;
  display: flex;
  margin-bottom: 20px;
}

.article-view-left {
  width: 20%;
  height: 100%;

  .search {
    margin: 10px 0 0 0;
    border: none;
    background-color: rgb(83, 82, 85);
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;

    .search-box {
      width: 100%;

      .search-input {
        width: 100%;
      }

      :deep(.el-input__wrapper) {
        --el-input-border-color: rgb(83, 82, 85);
        --el-input-focus-border-color: rgb(255, 255, 255);
        background-color: transparent;
      }

      :deep(.el-input__inner) {
        color: #ffffff;
      }
    }
  }

  .article-view-left-other {
    margin: 10px 0 0 0;
    border: none;
    background-color: rgb(83, 82, 85);
    height: 250px;

    .article-view-left-other-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 1.1rem;
      font-weight: bold;
      color: white;
      padding: 10px 12px;

      .reset {
        background-color: #ff9800;
        color: #ffffff;
        border: none;
      }

      .reset:hover {
        background-color: #ffd895;
        color: #e67112;
      }
    }

    :deep(.el-menu) {
      border-right: none;
      background-color: rgb(83, 82, 85);
    }

    :deep(.el-menu-item) {
      height: 40px;
      line-height: 40px;
      padding: 0 12px !important;
      margin-top: 10px;
    }

    .article-view-content-menu {
      margin-top: 10px;

      .menu-item-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        color: #ffffff;
      }

      .category-name {
        font-size: 0.95rem;
        font-weight: bold;
      }

      .count-badge {
        background-color: #ff9800;
        color: #ffffff;
        padding: 0px 10px;
        border-radius: 4px;
        font-size: 0.85rem;
        font-weight: bold;
        min-width: 24px;
        text-align: center;
      }
    }
  }

  :deep(.el-menu-item:hover) {
    background-color: rgb(63, 62, 65) !important;
  }

  :deep(.el-menu-item:hover) .menu-item-content {
    color: #ffd04b;
  }

  :deep(.el-menu-item.is-active) .menu-item-content {
    color: #ffd04b;
  }


}

.article-view-right {
  /* background-color: green; */
  margin-left: 15px;
  width: 80%;
  height: auto;
  display: flex;
  flex-direction: column;

  :deep(.el-card) {
    width: 100%;
    margin: 0;

  }

  :deep(.el-card__body) {
    padding: 15px 0 0 0;
    height: 100%;
  }

  .article-card {
    margin: 0 0 20px 0;
    height: 200px;
    padding: 15px 15px 15px 30px;
    background-color: rgb(083, 082, 085);
    border: none;

    .article-content {
      display: flex;
      height: 100%;

      .article-info {
        margin: 10px 10px 10px 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 70%;
      }

      .article-title {
        font-size: 1.7rem;
        font-weight: bold;
        color: #ffffff;
        cursor: pointer;

        &:hover {
          color: #e67112;
        }
      }

      .article-else {
        font-size: 1rem;
        font-weight: bold;
        display: flex;

        .icon {
          width: 40px;
          height: 40px;
          background-color: #ffd895;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 20%;

          .el-icon {
            font-size: 30px;
            color: #e67112;
          }
        }

        .text {
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 17px;
          color: #ffffff;
          margin-left: 5px;
        }

        .text-category {
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 17px;
          color: #ffffff;
          margin-left: 5px;

          &:hover {
            color: #e67112;
          }
        }

      }
    }

    .article-image {
      margin: 0 auto;
      width: 30%;
    }

  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(.btn-prev),
    :deep(.btn-next) {
      background-color: #ffd895;
    }

    :deep(.el-pager li) {
      color: #000000 !important;
      background-color: #ffd895;
    }

    :deep(.el-select__wrapper) {
      background-color: #ffd895;
      border: 0;
    }

    :deep(.el-input) {
      border: 0;
    }

    :deep(.el-select__selected-item) {
      color: #000000;
    }
  }

  .article-detail {
    margin: 0;
    padding: 0 40px 30px 40px;
    background-color: rgb(83, 82, 85);
    border: none;
    color: #ffffff;
    line-height: 1.5;

    .back-button {
      background-color: #ffd895;
      color: #e67112;
      border: none;
      font-size: 15px;
      font-weight: bold;

      &:hover {
        color: #ffffff;
      }
    }


    .detail-header {
      margin: 20px 0 20px 0;

      .detail-title {
        font-size: 1.8rem;
        font-weight: bold;
        color: #ffffff;
        margin-bottom: 20px;
      }

      .detail-meta {
        font-size: 1rem;
        font-weight: bold;
        display: flex;

        .icon {
          width: 40px;
          height: 40px;
          background-color: #ffd895;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 20%;

          .el-icon {
            font-size: 30px;
            color: #e67112;
          }
        }

        .text {
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 17px;
          color: #ffffff;
          margin-left: 5px;
        }

        .text-category {
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 17px;
          color: #ffffff;
          margin-left: 5px;

        }

      }
    }

  }

}
</style>